package c;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

class Animal implements Comparable<Animal> {
    private String name;
    
    public Animal(String name) {
    	this.name = name;
    }
    
    public String toString() {
    	return name;
    }

	/* (non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Animal other = (Animal) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

	@Override
	public int compareTo(Animal animal) {
		// TODO Auto-generated method stub
		int len1 = name.length();
		int len2 = animal.name.length();
		
		if(len1 > len2) return 1;
		else if(len1 < len2) return -1;
		else return name.compareTo(animal.name);
	}
}

public class ComparableTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
        List<Animal> list = new ArrayList<Animal>();        
        SortedSet<Animal> set = new TreeSet<Animal>();
        
        addElements(list);
        addElements(set);
        
        Collections.sort(list);
        
        showElements(list);
        System.out.println();
        showElements(set);
        
	}
	
	private static void addElements(Collection<Animal> col) {
		col.add(new Animal("Cat"));
		col.add(new Animal("Fish"));
		col.add(new Animal("Giraffe"));
		col.add(new Animal("Dog"));
		col.add(new Animal("Chicken"));		
	}
	
	private static void showElements(Collection<Animal> col) {
		for(Animal element: col) {
			System.out.println(element);
		}
	}

}
